package vip.xiaonuo.auth.modular.login.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.auth.modular.login.service.SSOService;
import vip.xiaonuo.dev.api.DevConfigApi;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;

/**
 * 统一身份认证
 */
@Api(tags = "统一身份认证")
@Slf4j
@RestController
public class SSOController {
    @Autowired
    private SSOService ssoService;
    @Resource
    private DevConfigApi devConfigApi;
    private String pc_frontend_base_url;
    private String h5_frontend_base_url;

    @PostConstruct
    public void init() {
        pc_frontend_base_url = devConfigApi.getValueByKey("PC_FRONTEND_BASE_URL");
        h5_frontend_base_url = devConfigApi.getValueByKey("H5_FRONTEND_BASE_URL");
    }

    @GetMapping("/sso/authorize")
    public void authorize(String client, HttpServletResponse response) throws IOException, NoSuchAlgorithmException {
        response.sendRedirect(ssoService.authorize(client));
    }

    /**
     * the endpoint for the sso/authorize,
     * get the code and state from url parameters.
     * get the code_verifier which generated by the previous step according to the state param.
     *
     * @param code
     * @param state
     * @param response
     * @throws IOException
     */
    @GetMapping("/sso/token")
    public void token(String code, String state, HttpServletResponse response) throws IOException {
        response.sendRedirect(ssoService.token(code, state));
    }

    @GetMapping("/signin-oidc")
    public void signInOidc(String code, String state, HttpServletResponse response) throws IOException {
        response.sendRedirect(ssoService.token(code, state));
    }

    @GetMapping("/sso/logout")
    public void logout(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", " text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String pcLogin = String.format("%s/login", pc_frontend_base_url);
        String h5Login = String.format("%s/pages/common/login/index", h5_frontend_base_url);
        String html = "<!DOCTYPE html><html>" +
                "<head>" +
                "<script>" +
                "if(/Mobi|Android|iPhone/i.test(navigator.userAgent)) { window.document.location = '%s'}" +
                "else { window.document.location = '%s' }" +
                "</script>" +
                "</head>" +
                "<body>" +
                "<span>页面跳转中,请勿关闭...</span>" +
                "</body>";
        out.print(String.format(html, h5Login, pcLogin));
        out.flush();
        out.close();
    }
}
